<?php

namespace app\system\controller\user;

use app\common\controller\System;
use Throwable;
use ba\Random;
use app\admin\model\User as UserModel;
use think\facade\Db;
use think\db\exception\PDOException;
use think\exception\ValidateException;

use ba\Exception;

class User extends System
{
    /**
     * @var object
     * @phpstan-var UserModel
     */
    protected object $model;


    protected array $withJoinTable = [];

    protected string|array $quickSearchField = ['username', 'nickname'];


    public function initialize(): void
    {

        parent::initialize();
        $this->model = new UserModel();
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo():void{
        $user_id = $this->request->get('user_id');
        $result = $this->model->find($user_id);
        $this->success('', $result);
    }

    /**
     * 设置代购费
     */
    public function agencyFee($id = null):void {
        $data = $this->request->post();
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        if ($this->request->isPost()) {
            if(empty($data['agency_fee']) || $data['agency_fee'] < 0){
                $agency_fee = 0;
            }elseif($data['agency_fee'] > 100){
                $agency_fee = 100;
            }else{
                $agency_fee = $data['agency_fee'];
            }
            $agency_fee = (int) $agency_fee;
            $update = [
                'agency_fee' => $agency_fee,
                'update_time' => $this->timestamp
            ];

            $result = Db::name('user')->where(['id' => $data['id']])->update($update);
            if($result){
                $this->success('', [
                    'agency_fee' => $agency_fee
                ]);
            }else{
                $this->error();
            }
        }

    }

    /**
     * 查看
     * @throws Throwable
     */

    public function index(): void
    {

        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withoutField('password,salt')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }



    /**
     * 编辑
     * @param string|int|null $id
     * @throws Throwable
     */
    public function edit(string|int $id = null): void
    {

        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();

            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);

            $password = $this->request->post('password', '');
            if ($password) {
                $this->model->resetPassword($id, $password);
            }
            if(isset($data['password'])) unset($data['password']);
            $email = $this->request->has('email') ? $this->request->post('email') : '';
            if (!empty($email)) {
                $where = [
                    ['email', '=', $email],
                    ['id', '<>', $row['id']],
                    ['system_substation_id', '=', $this->substation_id]
                ];
                if (db::name('admin')->where($where)->find()) $this->error(__('Email already exists'));
            }





            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

            parent::edit();
        }

        unset($row->salt);
        $row->password = '';
        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 重写select
     * @throws Throwable
     */
    public function select(): void
    {

        $this->request->filter(['strip_tags', 'trim']);

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        foreach ($res as $re) {
            $re->nickname_text = $re->username . '(ID:' . $re->id . ')';
        }

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
}